/**
 * Copyright (c) 2011, UNC-Chapel Hill

   All rights reserved.

   Redistribution and use in source and binary forms, with or without modification, are permitted provided 
   that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and 
    * the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the 
    * following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the UNC-Chapel Hill nor the names of its contributors may be used to endorse or promote 
    * products derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package edu.unc.ils.biosis.parser;

import java.io.BufferedReader;

import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;

public class BIOSISParser 
{
    public static void main(String[] args) throws Exception 
    {
        // Get the options specified
        CommandLineParser parser = new BasicParser( );

        Options options = getOptions();
        CommandLine commandLine = parser.parse( options, args );

        if (commandLine.hasOption("h"))
        {
            // Print the help message
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp( "java " + BIOSISParser.class.getCanonicalName(), options );
        }
        else
        {
            String filePath = commandLine.getOptionValue("f");
            boolean doTaxa = commandLine.hasOption("t");
            boolean doConcepts = commandLine.hasOption("c");
            boolean doGeographic = commandLine.hasOption("g");
            
            File file = new File(filePath);
            
            BIOSISParser bp = new BIOSISParser();
            
            if (doTaxa)
                bp.printTaxa(file);
            
            if (doConcepts)
                bp.printConcepts(file);
            
            if (doGeographic)
                bp.printGeographic(file);
        }
    }
    
    /**
     * Returns the CLI options
     * @return
     */
    public static Options getOptions()
    {
        Options options = new Options();
        Option filePath = new Option("f", true, "Path export file in ISI export format");
        filePath.setRequired(false);
        options.addOption(filePath);
        
        options.addOption("h", false, "Print this help message");
        options.addOption("t", false, "Output taxanomic names");
        options.addOption("c", false, "Output concepts");
        options.addOption("g", false, "Output geographic names");
       
        return options;
    }
	
    /**
     * Print the taxon data for each record. This includes the super taxa, BIOSIS classifier and 
     * variants found in the article by the BIOSIS indexer.
     * 
     * @param file
     * @throws Exception
     */
	protected void printTaxa(File file) throws Exception
	{
		BufferedReader br = new BufferedReader(new FileReader(file));
		String line;
		String text = "";
		while ((line = br.readLine()) != null)
			text += line + "\n";

		Map<String, BIOSISRecord> records = BIOSISParser.parse(text);
		for (String an: records.keySet()) 
		{
		    
		    
			BIOSISRecord record = records.get(an);
			List<BIOSISTaxonomicData> taxa = record.getTaxonData();
			for (BIOSISTaxonomicData taxon: taxa) 
			{
			    StringBuffer buffer = new StringBuffer();
			    buffer.append(record.getAccessionNumber() + "|");
			    
                String superTaxa = taxon.getSuperTaxa().get(0);
                buffer.append(superTaxa + "|");
                
                String classifierName = taxon.getClassifierName();
                buffer.append(classifierName + "|");
                
				List<String[]> variants = taxon.getVariants();
				if (variants.size() > 0) 
				{
					for (String[] variantDetails: variants)
					{
						String variant = variantDetails[0];
						buffer.append(variant + "|");
					}
				}
				System.out.println(buffer);
			}
			
		}
	}
	
	/**
	 * Print the BIOSIS concept codes for the record. This includes the code and value.
	 * @param file
	 * @throws Exception
	 */
    protected void printConcepts(File file) throws Exception
    {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        String text = "";
        while ((line = br.readLine()) != null)
            text += line + "\n";

        Map<String, BIOSISRecord> records = BIOSISParser.parse(text);
        for (String an: records.keySet()) 
        {
            BIOSISRecord record = records.get(an);
            List<String[]> conceptCodes = record.getConceptCodes();
            for (String[] concept: conceptCodes) 
            {
                StringBuffer buffer = new StringBuffer();
                buffer.append(record.getAccessionNumber() + "|");
                
                buffer.append(concept[0] + "|");
                buffer.append(concept[1] + "|");
                System.out.println(buffer);
            }
        }
    }
    
    /**
     * Print geographic information from the record.
     * @param file
     * @throws Exception
     */
    protected void printGeographic(File file) throws Exception
    {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        String text = "";
        while ((line = br.readLine()) != null)
            text += line + "\n";

        Map<String, BIOSISRecord> records = BIOSISParser.parse(text);
        for (String an: records.keySet()) 
        {
            BIOSISRecord record = records.get(an);
            List<String> geographicNames = record.getGeographicData();
            for (String geographicName: geographicNames) 
            {
                StringBuffer buffer = new StringBuffer();
                buffer.append(record.getAccessionNumber() + "|");
                buffer.append(geographicName);
                System.out.println(buffer);
            }
        }
    }
	
	
	public static Map<String, BIOSISRecord> parse(String text) 
	{
		Map<String, BIOSISRecord> records = new HashMap<String, BIOSISRecord>();
		
		String[] lines = text.split("\\\n");
		String recordText = "";
		for (String line: lines) 
		{
			if (line.startsWith(BIOSISFields.END_OF_RECORD.getFieldName())) {
				BIOSISRecord rec = BIOSISRecord.parse(recordText);
				records.put(rec.getAccessionNumber(), rec);
				recordText = "";
			}
			else
				recordText += line + "\n";
			
		}
		return records;
	}
	
	public static Map<String, String> parseText(String text) 
	{
		Map<String, String> records = new HashMap<String, String>();
		
		String[] lines = text.split("\\\n");
		String recordText = "";
		for (String line: lines) 
		{
			if (line.startsWith(BIOSISFields.END_OF_RECORD.getFieldName())) {
				BIOSISRecord rec = BIOSISRecord.parse(recordText);
				recordText += "\n" + BIOSISFields.END_OF_RECORD.getFieldName() + "\n";
				records.put(rec.getAccessionNumber(), recordText);
				recordText = "";
			}
			else
				recordText += line + "\n";
			
		}
		return records;
	}
}
